// pages/login/index.js
const App = getApp()
const userBehaviors = require('../../common/behaviors/userBehaviors')
const loginApi = require('../../common/api/login')
const MESSAGE = require('../../common/config/message.config.js')
const checkData = require('../../common/utils/check.js')
let that
Page({
  behaviors: [userBehaviors],
  /**
   * 页面的初始数据
   */
  data: {
    // scroll-into-view
    scrollId: "",
    active: 0,
    TabCur: 0,
    get_openid: '',
    loginTypeArr: [{
        type: 0,
        text: '帐号密码',
        icon: "icon-zhanghaoguanli",
        color: "#ea6b65"
      },
      {
        type: 1,
        text: '微信',
        icon: "icon-weixin",
        color: "#28c445"
      }
    ],
    loginType: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    that = this;
    try {
      const openid = await loginApi.getOpenID()
      this.setData({
        get_openid: openid
      })
    } catch (error) {
      console.error(error)
    }

  },

  //滑块
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
    console.log('当前id', e.currentTarget.dataset);
  },
  // 学院选择
  ChangeCollege: function (e) {
    console.log('学院picker发送选择改变，携带值为', e.detail.value)
    let CollegeName = this.data.College[e.detail.value]
    console.log('测试学院值', CollegeName);
    this.setData({
      CollegeIdx: e.detail.value,
      ['enroll.CollegeId']: CollegeName
    })
  },
  // 性别
  ChangeGender: function (e) {
    console.log('性别picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      GenderIdx: e.detail.value,
      ['enroll.gender']: e.detail.value
    })
  },
  // 切换登陆方式
  changeLoginType: function (e) {
    this.setData({
      loginType: e.detail.value
    })
  },

  // 注册身份选择
  ChangeEnroll: function (e) {
    console.log('身份picker发送选择改变，携带值为', e.detail.value)
    // 获取身份id的值
    console.log("身份id " + this.data.identity[e.detail.value].id)
    this.setData({
      UserElIdx: e.detail.value,
      ['enroll.IdentityId']: this.data.identity[e.detail.value].id
    })

  },

  // 将注册信息转登录输入框
  inputAdd: function () {
    this.setData({
      ['login.loginUser']: this.data.enroll.enrollUser,
      ['login.loginPassword']: this.data.enroll.enrollPassword,
    })
  },
  // 清空输入框
  inputReset: function () {
    this.setData({
      TabCur: 0,
      ['enroll.enrollUser']: null,
      ['enroll.enrollPassword']: '',
      ['enroll.email']: '',
      UserElIdx: null,
      CollegeIdx: null,
      GenderIdx: null,
    })
  },
  // 弹窗
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  // 获取input输入的值
  handleChange(e, key) {
    const {
      detail,
      currentTarget
    } = e
    console.log('detail', detail);
    console.log('currentTarget', currentTarget);
    this.setData({
      [`login.${currentTarget.id}`]: detail.value,
      [`enroll.${currentTarget.id}`]: detail.value,
      // input输入的时候把页面往上挪，显出注册按钮
      scrollId: "y-" + 1
    })
  },

  //登录
  async login() {
    let loginData;
    if (this.data.loginType == 0) {
      // 帐号密码登陆
      const account = checkData.checkEmpty(Number(that.data.login.loginUser), MESSAGE.ERROR_MESSAGE.CHECKEDACCOUNT)
      const password = checkData.checkEmpty(that.data.login.loginPassword, MESSAGE.ERROR_MESSAGE.CHECKEDPWD)
      if (!account || !password) return
      loginData = {
        account,
        password
      }

    }
    App.toast.showLoading('登陆中')
    //登录之前是否已经授权注册
    try {
      await loginApi.login(loginData);
      App.toast.showToast(MESSAGE.SUCCESS.LOGINSUCCESS)
      this.logRouting()
    } catch (error) {
      console.log(error)
      if (error == 1) {
        this.setData({
          TabCur: 1,
        })
      } else {
        console.error(error)
      }
    } finally {
      App.toast.hideLoading()
    }
  },

  // 注册效验
  check() {
    // 身份
    let identityId = checkData.checkEmpty(that.data.enroll.IdentityId, MESSAGE.ERROR_MESSAGE.CHECKEDUSEREL)
    // 学院
    let collegeId = checkData.checkEmpty(that.data.enroll.CollegeId, MESSAGE.ERROR_MESSAGE.CHECKEDCOLLEGE)
    // 性别
    let gender = checkData.checkEmpty(that.data.GenderIdx, MESSAGE.ERROR_MESSAGE.CHECKEDGENDER)
    // 邮箱
    let account = checkData.checkEmpty(that.data.enroll.enrollUser, MESSAGE.ERROR_MESSAGE.CHECKEDACCOUNT)
    let email = checkData.checkEmail(that.data.enroll.email, MESSAGE.ERROR_MESSAGE.CHECKEDEMAIL)

    let papassword = checkData.checkEmpty(that.data.enroll.enrollPassword, MESSAGE.ERROR_MESSAGE.CHECKEDPWD)
    if (!identityId || !collegeId || !gender || !account || !email || !papassword) return
    const fromData = {
      identityId,
      collegeId,
      gender,
      account,
      email,
      papassword
    }
    that.enroll(fromData)
  },
  // 注册 
  enroll(fromData) {
    wx.getUserProfile({
      desc: '获取用户信息',
      success: async res => {
        console.log(res)
        try {
          const regRes = await loginApi.registe({
            ...fromData,
            wxUser: res.userInfo
          })
          if (regRes == -1) {
            this.setData({
              TabCur: 0,
            })
          } else {
            that.inputAdd()
            that.inputReset()
          }
        } catch (error) {
          console.error(error)
        }

      }
    })

  },
  logRouting() {
    // 根据身份标识跳到对应的page
    setTimeout(() => {
      App.toast.showToast('即将跳转')
      let lowercaseIdentityId = App.cache.getCache('get_identityId').toLowerCase()
      App.route.relTo('/pages/' + lowercaseIdentityId + '/home/index')
    }, 1500)
  }

})